package ZombieTriggers;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import java.util.logging.Logger;

import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.CreatureType;
import org.bukkit.entity.Player;
import org.bukkit.entity.Zombie;
import org.bukkit.event.Event;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.EntityCombustEvent;
import org.bukkit.event.entity.EntityListener;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerListener;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;

public class Main extends JavaPlugin{
	public Logger log=Logger.getLogger("Minecraft");
	public PluginDescriptionFile pdf;
	public FileConfiguration cfg;
	private ArrayList<Trigger> triggers=new ArrayList<Trigger>();
	private ArrayList<String> editors=new ArrayList<String>();
	boolean TriggersEnabled=false;

	public void onEnable(){
		PluginManager pm=getServer().getPluginManager();
		pListener pL=new pListener();
		eListener eL=new eListener();
		pm.registerEvent(Event.Type.PLAYER_INTERACT, pL, Event.Priority.High, this);
		pm.registerEvent(Event.Type.PLAYER_MOVE, pL, Event.Priority.High, this);
		pm.registerEvent(Event.Type.ENTITY_COMBUST, eL, Event.Priority.High, this);
		if(!this.getDataFolder().exists())this.getDataFolder().mkdirs();
		LoadCfg();
		editors.clear();
		pdf=this.getDescription();
        log.info(pdf.getName()+" v"+pdf.getVersion()+" by "+pdf.getAuthors().toString()+" enabled." );
	}

	public void onDisable(){
		try{
			SaveCfg();
		}catch(IOException e){log.info(e.getLocalizedMessage());}
        log.info(pdf.getName()+" v"+pdf.getVersion()+" by "+pdf.getAuthors().toString()+" disabled." );
	}
	
    public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
        String commandName = command.getName().toLowerCase();
        if(sender instanceof Player){
    		Player p = (Player)sender;
	    	if(commandName.equals("tr")){
	    		if(args.length==0){
	    			String s="ZombieTriggers plugin available commands:\n/tr list - list all triggers\n/tr edit - toggle triggers edit mode";
	    			for(String m:s.split("\n"))
	    				p.sendMessage(m);
	    		}else if(args[0].equals("list")){
    				p.sendMessage(ChatColor.YELLOW+"Current triggers and its locations:");
	    			for(Trigger sp:triggers)
	    				p.sendMessage(ChatColor.AQUA+""+sp.id+" -> "+ChatColor.YELLOW+""+sp.w+"@"+ChatColor.GREEN+""+sp.x+":"+sp.y+":"+sp.z);
	    		}else if(args[0].equals("edit")){
	    			if(editors.contains(p.getName())){
	    				editors.remove(p.getName());
	    				p.getInventory().remove(p.getInventory().first(new ItemStack(Material.WOOD_HOE)));
	    				p.getInventory().remove(p.getInventory().first(new ItemStack(Material.WOOD_SPADE)));
	    				p.sendMessage(ChatColor.DARK_GREEN+"Triggers edit mode disabled!");
	    			}else{
	    				editors.add(p.getName());
	    				p.getInventory().addItem(new ItemStack(Material.WOOD_HOE),new ItemStack(Material.WOOD_SPADE));
	    				p.sendMessage(ChatColor.GREEN+"Triggers edit mode enabled!");
	    			}
	    		}
	    	}
        }
    	return false;
    }
	
	public void LoadCfg(){
		File f;
		f=new File(this.getDataFolder()+"\\config.yml");
		if(f.exists()){
			FileConfiguration cfg=YamlConfiguration.loadConfiguration(f);
			TriggersEnabled=cfg.getBoolean("enable triggers on server start",false);	
		}

		triggers.clear();
		f=new File(this.getDataFolder()+"\\triggers.yml");
		if(f.exists()){
			FileConfiguration fc=YamlConfiguration.loadConfiguration(f);
			for(String key:fc.getKeys(false))
				triggers.add(
					new Trigger(
						Integer.parseInt(key),
						fc.getString(key+".world",getServer().getWorlds().get(0).getName()),
						fc.getInt(key+".pos.x",0),
						fc.getInt(key+".pos.y",0),
						fc.getInt(key+".pos.z",0)
					)
				);
		}
	}
	
	public void SaveCfg() throws IOException{
		FileConfiguration cfg=YamlConfiguration.loadConfiguration(new File(this.getDataFolder()+"\\config.yml"));
		cfg.set("enable triggers on server start",cfg.getBoolean("enable triggers on server start",false));
		cfg.save(this.getDataFolder()+"\\config.yml");
		
		FileConfiguration fc=YamlConfiguration.loadConfiguration(new File(this.getDataFolder()+"\\triggers.yml"));
		for(Trigger sp:triggers){
			fc.set(sp.id+".world",sp.w);
			fc.set(sp.id+".pos.x",sp.x);
			fc.set(sp.id+".pos.y",sp.y);
			fc.set(sp.id+".pos.z",sp.z);	
		}
		fc.save(this.getDataFolder()+"\\triggers.yml");
	}

	public class pListener extends PlayerListener {			
		public void onPlayerInteract(PlayerInteractEvent ev){
			Player p = ev.getPlayer();
			if(ev.getAction().equals(Action.LEFT_CLICK_AIR)||ev.getAction().equals(Action.LEFT_CLICK_BLOCK))
				if(editors.contains(p.getName()))
					if(p.getItemInHand().getType().equals(Material.WOOD_HOE)){
						Trigger sp=new Trigger(
							triggers.size(),
							ev.getClickedBlock().getWorld().getName(),
							ev.getClickedBlock().getX(),
							ev.getClickedBlock().getY(),
							ev.getClickedBlock().getZ()
						);
						triggers.add(sp);
						p.sendMessage(ChatColor.YELLOW+"Trigger created at "+ChatColor.AQUA+sp.w+"@"+sp.x+":"+sp.y+":"+sp.z);
						ev.setCancelled(true);
					}else if(p.getItemInHand().getType().equals(Material.WOOD_SPADE)){
						for(Trigger sp:triggers)
							if(sp.isPos(ev.getClickedBlock().getX(),ev.getClickedBlock().getY(),ev.getClickedBlock().getZ())){
								p.sendMessage(ChatColor.YELLOW+"Trigger at "+ChatColor.AQUA+sp.w+"@"+sp.x+":"+sp.y+":"+sp.z+ChatColor.YELLOW+" deleted!");
								triggers.remove(sp);
								break;
							}
						ev.setCancelled(true);
					}
		}
		public void onPlayerMove(PlayerMoveEvent ev){
			World w=ev.getTo().getWorld();
			FORSTART:for(Trigger sp:triggers)
				for(int x=-1;x<2;x++)
					for(int z=-1;z<2;z++)
						if(sp.isPos(ev.getTo().getBlockX()+x,ev.getTo().getBlockY()-1,ev.getTo().getBlockZ()+z)){
							boolean bx=new Random().nextBoolean(),by=new Random().nextBoolean(),bz=new Random().nextBoolean();
							SECFOR:for(int tx=(bx?-10:10);(bx?tx<11:tx>-11);tx+=(bx?1:-1))
								for(int ty=(by?-3:3);(by?ty<4:ty>-5);ty+=(by?1:-1))
									for(int tz=(bz?-10:10);(bz?tz<11:tz>-11);tz+=(bz?1:-1))
										if(new Random().nextInt(1000)==0){
											Block b=w.getBlockAt(sp.x+tx,sp.y+ty,sp.z+tz);
											if((b.getTypeId()!=0)&&(b.getRelative(0,1,0).getTypeId()==0)&&(b.getRelative(0,2,0).getTypeId()==0)){
												w.spawnCreature(b.getLocation(),CreatureType.ZOMBIE);
												log.info("ZOMBIE SPAWNED!");
												break SECFOR;
											}
										}
							break FORSTART;
						}
		}
	}

	public class eListener extends EntityListener {			
		public void onEntityCombust(EntityCombustEvent ev){
			if(ev.getEntity() instanceof Zombie){
				((Zombie)ev.getEntity()).setFireTicks(0);
				ev.setCancelled(true);
			}
		}
	}

}
